$m(function (args) {
    var $this = $(this.element).closest("body");
    this.jobDialog = null;
    this.flowsParam = {};
    var that = this;
    flowInfo = {};
    var allDatas = [];
    flows = [];
    var allCount = 0;
    var seleccount = 0;
    var rowDatas = {};
    var successCount = 0;
    var failedCount = 0;
    var nowState = "";
    var runningDatas = [];//已启动的数据集
    var unstartDatas = [];//未启动的数据集
    var flowIdandStatus = [];//用于从服务详情页面点击返回，页面刷新后的行判断
    // 定义一个判断用户是否点击筛选-查询的标识
    var isSearch = false;
    // 定义一个存储点击筛选-查询时，筛选里所有框的信息
    var searchData = {};
    var alert = function (text) {
        $("<div/>").alert({
            msg: text,
            title: TempoUtils.locale("mine.prompt")
        });
    }

    $this.find("#jobContainer").layout({
        north: {
            resizable: false,
            size: 100,
            spacing_open: 0
        },
        center: {
            onresize: TempoUtils.throttle(function () {
            }, 200, true)
        }
    });


    //列表点击事件
    var grayClickEvent = function () {
        //为筛选框添加图标提示
        $(".sizer").blur(function () {
            // 获取筛选div里的搜索input框
            var inputs = $('#shaixuanDiv').find('input');
            // 定义是否有数据标识 true表示有数据
            var hasValue = false;
            for (var i = 0; i < inputs.length; i++) {
                if (inputs.eq(i).val().trim() != "") {
                    hasValue = true;
                    break;
                }
            }
            // 如果搜索框中有值，则显示图标
            if (hasValue) {
                $("#ifshaixuan").removeAttr('style');
                $(".sizer-reset").css("color", "#5185e4")
            } else {
                $("#ifshaixuan").hide();
            }
        });
        //为重置按钮添加点击事件
        $("#sizer-reset").click(function () {
            // 将搜索状态改为false，并清空筛选数据
            isSearch = false;
            searchData = {};
            $("#ifshaixuan").hide();
            //将日期选择器清除，并重新初始化
            $("input[name='laststarttime']").datepicker("destroy");
            $("input[name='lastendtime']").datepicker("destroy");
            $(".tempo-sizer-inputright input").val("");
            initOrrefresh(false);
            get_sizerdata(nowState);
        });
        //根据点击启动状态按钮改变按钮颜色
        var changeBtColor = function (bt1, bt2) {
            bt1.css("color", "dimgray");
            bt1.css("background-color", "#eee");
            bt2.css("color", "dimgray");
            bt2.css("background-color", "#eee");
        }
        var getDatabyState = function (status) {
            that.grid.datagrid('reloadGrid', {status: status});
        }

        var bt_complete = $("#tempo-gray-allbt");
        var bt_unstart = $("#tempo-gray-unrunbt");
        var bt_startsuc = $("#tempo-gray-runningbt");
        //为启用的按钮添加点击筛选条件
        $("#tempo-gray-runningbt").off('click').on('click', function () {
            nowState = "running";
            runningDatas = [];
            $(".after_select").hide();
            $(this).css("color", "#5185e4");
            $(this).css("background-color", "#dfe9fd");
            changeBtColor(bt_complete, bt_unstart);
            getDatabyState("running");
        });
        //为禁用的按钮添加点击筛选条件
        $("#tempo-gray-unrunbt").off('click').on('click', function () {
            nowState = "unstart";
            unstartDatas = [];
            $(".after_select").hide();
            $(this).css("color", "#5185e4");
            $(this).css("background-color", "#dfe9fd");
            changeBtColor(bt_startsuc, bt_complete);
            getDatabyState("unstart");
        });
        //为“全部”按钮绑定筛选条件
        $("#tempo-gray-allbt").off('click').on('click', function () {
            nowState = "all";
            $(".after_select").hide();
            $(this).css("color", "#5185e4");
            $(this).css("background-color", "#dfe9fd");
            changeBtColor(bt_startsuc, bt_unstart);
            getDatabyState("all");
        });
        //点击取消发布，删除本条监测信息方法
        $(".tempo-gray-unpublish").off('click').on('click', function (e) {
            var id = $(this).attr('serviceId');

            $('<div/>').confirm({
                msg: TempoUtils.locale("mine.isOrNo"),
                ok: function () {
                    var progressbar = $("<div/>").tempoprogressbar();
                    $.ajax({
                        url: contextPath + "/api/ai/mine/gray/unpublish",
                        data: {
                            id: id,
                        },
                        dataType: 'json',
                        type: 'post',
                        traditional: true,
                        success: function (result) {
                            progressbar.tempoprogressbar("destroy");
                            if (result.success) {
                                $this.find('.cglist-view-container').empty();
                                $m.loadPage(contextPath + "/api/ai/app/schedule/view/grayhronize_server", $this.find('.cglist-view-container'));
                                nowSizerStatus();
                            } else {
                                TempoUtils.showTip(result.message);
                            }
                        },
                        error: function (e) {
                            progressbar.tempoprogressbar("destroy");
                            nowSizerStatus();
                        }
                    });
                }
            });

        });

        //灰度服务批量启用
        $('.tempo-graystart-service ').off('click').on('click', function () {
            var ids = [];
            var allselectDatas = that.grid.datagrid("getSelectRowData");
            for (var i = 0; i < allselectDatas.length; i++) {
                ids.push(allselectDatas[i].GRAYID);
            }
            $("<div>").confirm({
                width: 500,
                height: 197,
                msg: "已选中" + allselectDatas.length + "个任务，是否确定批量启用？",
                ok: function () {
                    $(".after_select").hide();
                    var process = $("<div/>").tempoprogressbar();
                    $.ajax({
                        url: contextPath + "/api/ai/mine/gray/gray-batch-start",
                        type: 'post',
                        data: {
                            ids: ids.toString()
                        },
                        success: function (obj) {
                            process.tempoprogressbar("destroy");
                            that.grid.jqGrid().trigger("reloadGrid");

                        }, error: function (obj) {
                            process.tempoprogressbar("destroy");
                        }
                    });

                }
            });

        });

        //灰度服务批量禁用
        $('.tempo-batchstop-grayservice').off('click').on('click', function () {
            var ids = [];
            var allselectDatas = that.grid.datagrid("getSelectRowData");
            for (var i = 0; i < allselectDatas.length; i++) {
                ids.push(allselectDatas[i].GRAYID);
            }
            $("<div>").confirm({
                width: 500,
                height: 197,
                msg: "已选中" + allselectDatas.length + "个任务，是否确定批量禁用？",
                ok: function () {
                    $(".after_select").hide();
                    var process = $("<div/>").tempoprogressbar();
                    $.ajax({
                        url: contextPath + "/api/ai/mine/gray/gray-batch-stop",
                        type: 'post',
                        data: {
                            ids: ids.toString()
                        },
                        success: function (obj) {
                            process.tempoprogressbar("destroy");
                            that.grid.datagrid('reloadGrid');
                        }, error: function (obj) {
                            process.tempoprogressbar("destroy");
                        }
                    });

                }
            });

        });

        //批量取消发布
        $(".tempo-batch-gray-unpublish").off('click').on('click', function (e) {
            var allselectDatas = that.grid.datagrid("getSelectRowData");
            var rowIds = that.grid.datagrid("getSelectRowIds");
            var idList = [];
            for (var i = 0; i < rowIds.length; i++) {
                idList.push(allselectDatas[i].GRAYID);
            }
            if (idList.length == 0) {
                alert(TempoUtils.locale("mine.serviceList"));
                return;
            }
            $("<div>").confirm({
                width: 500,
                height: 197,
                msg: "已选中" + rowIds.length + "个任务，是否确定批量取消发布？",
                ok: function () {
                    var process = $("<div/>").tempoprogressbar();
                    $(".after_select").hide();
                    $.ajax({
                        url: contextPath + '/api/ai/mine/gray/batch-unpublish',
                        type: 'post',
                        traditional: true,
                        data: {
                            id: idList,
                        },
                        success: function (rs) {
                            process.tempoprogressbar("destroy");
                            var url = "/api/ai/app/schedule/view/grayhronize_server";
                            if (rs.success) {
                                url = "/api/ai/app/schedule/view/grayhronize_server";
                            }
                            TempoUtils.showTip(rs.message);
                            $this.find('.cglist-view-container').empty();
                            $m.loadPage(contextPath + url, $this.find('.cglist-view-container'));
                            nowSizerStatus();
                        },
                        error: function (e) {
                            process.tempoprogressbar("destroy");
                            nowSizerStatus();
                        }
                    });

                }
            });

        });
        var get_sizerdata = function (statasParam) {
            var publishtime_pre = $("input[name='laststarttime']").datepicker('getDate');
            var publishtime_end = $("input[name='lastendtime']").datepicker('getDate');
            var sizer_data = {
                serverName: $("input[name='serveName']").val().trim(),
                workspaceName: $("input[name='workspaceName']").val().trim(),
                jobcreator: $("input[name='jobcreator']").val().trim(),
                publishtime_pre: publishtime_pre ? DateUtils.formatDate(publishtime_pre, 'yyyy-MM-dd') : null,
                publishtime_end: publishtime_end ? DateUtils.formatDate(publishtime_end, 'yyyy-MM-dd') : null,
                status: statasParam
            };
            searchData = sizer_data;
            that.grid.datagrid("reloadGrid", searchData);
        }
        //筛选框查询事件
        $(".queryBtn").off('click').on('click', function () {
            $("#shaixuanDiv").hide();
            isSearch = true;
            get_sizerdata(nowState);

        });
    }
    /*
     * 判断当前选中的是在哪种筛选状态下
     */
    var nowSizerStatus = function () {
        if (nowState == '1') {
            $("#tempo-gray-runningbt").trigger('click')
        } else if (nowState == '0') {
            $("#tempo-gray-unrunbt").trigger('click');
        } else if (nowState == "all") {
            $("#tempo-gray-allbt").trigger('click');

        } else {
            $("#tempo-gray-allbt").trigger('click');
        }
    }

    /**
     * 启用/禁用灰度服务
     * @param serviceId
     * @param status
     */
    var updateGrayServiceStatus = function (serviceId, status) {
        $.ajax({
            url: contextPath + '/api/ai/mine/gray/start-or-stop-gray-service',
            type: 'post',
            data: {
                id: serviceId,
                status: status
            },
            success: function (data) {
                rowDatas[data.data.id].FLOWSTATUS = data.data.status;
                if (data.data.status === "0") {
                    that.grid.jqGrid().trigger("reloadGrid");
                } else if (data.data.status === "1") {
                    that.grid.jqGrid().trigger("reloadGrid");
                }
            }
        });
    }

    /**
     * 列表事件
     */
    var bindJobGridEvent = function () {
        var grid = $this.find('#mine-opt-job-grid');
        //点击灰度服务名称，跳转任务详情界面
        grid.find('.tempo-datagrid-trigger-name').off('click').on("click", function (e) {
            flowIdandStatus = [];
            var rowid = $(e.target).attr('rowid');
            window.syncServiceRowId = rowid;
            flowIdandStatus = [];
            var row = rowDatas[rowid];
            flowIdandStatus.push(rowid);
            viewDetail(row);
        });
        //点击同步服务1名称，跳转任务详情界面
        grid.find('.tempo-datagrid-trigger-sync1name').off('click').on("click", function (e) {
            var rowid = $(e.target).attr('rowid');
            window.syncServiceRowId = rowid;
            $.ajax({
                url: contextPath + "/api/ai/mine/gray/sync-data-job",
                type: 'post',
                data: {
                    id: rowid,
                },
                async: false,
                success: function (results) {
                    sync1ViewDetail(results.data[0]);
                }
            });
        });
        //点击同步服务2名称，跳转任务详情界面
        grid.find('.tempo-datagrid-trigger-sync2name').off('click').on("click", function (e) {
            var rowid = $(e.target).attr('rowid');
            window.syncServiceRowId = rowid;
            $.ajax({
                url: contextPath + "/api/ai/mine/gray/sync-data-job",
                type: 'post',
                data: {
                    id: rowid,
                },
                async: false,
                success: function (results) {
                    sync2ViewDetail(results.data[0]);
                }
            });
        });
        //点击启用
        grid.find('.tempo-gray-start').off('click').on("click", function (e) {

            var rowid = $(e.target).attr('serviceId');
            updateGrayServiceStatus(rowid, "0");
        });
        //点击禁用
        grid.find('.tempo-gray-stop').off('click').on("click", function (e) {

            var rowid = $(e.target).attr('serviceId');
            updateGrayServiceStatus(rowid, "1");
        })

    };

    var viewDetail = function (job) {
        openViewDetailDialog(job);
    };

    var sync1ViewDetail = function (job) {
        openSync1ViewDetailDialog(job);
    };

    var sync2ViewDetail = function (job) {
        openSync2ViewDetailDialog(job);
    };

    var sizerDivShow = function (one) {
        $("#shaixuanDiv").slideToggle();
        $(".tempo-sizer-icon").toggleClass("ui-icon tempo-ui-icon tempo-ui-icon-downarrows-thin");
        $(".tempo-sizer-icon").toggleClass("ui-icon tempo-ui-icon tempo-ui-icon-uparrows-thin");
        $(document).bind("click", function (e) {
            var target = $(e.target);
            if (target.closest(one).length == 0) {
                $("#shaixuanDiv").hide();
                $(".tempo-sizer-icon").toggleClass("ui-icon tempo-ui-icon tempo-ui-icon-uparrows-thin");
                $(".tempo-sizer-icon").toggleClass("ui-icon tempo-ui-icon tempo-ui-icon-downarrows-thin");
                $(document).off('click');
            }
        });
    }
    //筛选框弹出事件绑定
    $("#shaix").click(function () {
        sizerDivShow("#shaixuanDiv,#shaix,.tempo-sizer-icon,.ui-datepicker-title,.ui-datepicker-current,.mark,.ui-datepicker-close,.ui-datepicker-calendar,#ui-datepicker-div,.ui-datepicker-prev,.ui-datepicker-next ");
    });
    //筛选图标点击事件
    $(".tempo-sizer-icon").click(function () {
        sizerDivShow("#shaixuanDiv,#shaix,.tempo-sizer-icon,.ui-datepicker-title,.ui-datepicker-current,.mark,.ui-datepicker-close,.ui-datepicker-calendar,#ui-datepicker-div,.ui-datepicker-prev,.ui-datepicker-next ");
    });
    //当成功失败次数太多时显示不下，因此根据数量扩展外层div大小
    var extendDiv = function (num, object) {

        var oldWidth = object.width();
        if (num >= 100000 && num < 1000000) {
            object.css("width", oldWidth + 20);
        } else if (num >= 1000000) {
            object.css("width", oldWidth + 40);
        }
    }

    /**
     * 初始化列表
     */
    var initJobGrid = function () {
        $(".ui-jqgrid-htable ").css("width", "100%");
        that.grid = $this.find('#mine-opt-job-grid').datagrid({
            datatype: "json",
            url: contextPath + '/api/ai/mine/gray/gray-data-job?time=' + new Date().getTime(),
            postData: {},
            fit: true,
            autowidth: true,
            separator: true,//分割线
            mtype: 'POST',
            rownumbers: true,
            shrinkToFit: true,
            viewrecords: true,
            pagination: true,
            striped: true,
            loadonce: true,
            multiselect: true,
            showRefreshBth: true,
            //勾选后的触发事件
            onSelectRow: function () {
                var selecspan = $(".selectedSpan");
                var grid = $this.find('#mine-opt-job-grid');
                var selected = grid.datagrid("getSelectRowIds");
                $(".tempo-datagrid-trigger-name").css("color", "black");
                $(".tempo-datagrid-trigger-sync1name").css("color", "black");
                $(".tempo-datagrid-trigger-sync2name").css("color", "black");
                seleccount = selected.length;
                if (seleccount != 0) {
                    selecspan.text("已选择" + " " + seleccount + " " + "条");
                }
                $(".after_select").css("display", "");
                if (seleccount == 0) {
                    $(".after_select").css("display", "none");
                }
                //全选按钮是否选中
                if (that.grid.find("input").length == seleccount) {
                    that.grid.parent().parent().parent().find("input[id$='_mine-opt-job-grid']").prop("checked", true);
                }
            },
            colNames: ['GRAYID',
                'sync1Id',
                'sync2Id',
                '服务名称',
                '所属空间',
                '同步服务1',
                '同步服务2',
                '发布人',
                '发布时间',
                TempoUtils.locale("mine.publish-mine-job-grid-col-lastcosttime"),//'上一次执行耗时'
                '服务状态',
                TempoUtils.locale("mine.zhixingqingkuang"),
                TempoUtils.locale("mine.publish-mine-job-grid-col-opt")//'操作'
            ],
            colModel: [{
                name: 'GRAYID',
                hidden: true
            }, {
                name: 'sync1Id',
                hidden: true
            }, {
                name: 'sync2Id',
                hidden: true
            }, {
                name: 'GRAYNAME',
                hidden: false,
                sortable: false,
                formatter: function (obj, rows, grid) {
                    rowDatas[grid.GRAYID] = grid;
                    var html = "<a href='javascript:void(0);' class='tempo-datagrid-trigger-name' style='text-decoration: none' rowid='" + grid.GRAYID + "'>" + TempoMineUtils.encodeHTML(obj) + "</a>";
                    return html;
                }
            }, {
                name: 'WORKSPACENAME',//所属空间
                hidden: false,
                sortable: false,
                formatter: function (obj, rows, grid) {
                    if (obj == null) {
                        return "";
                    }
                    return obj.replace(/</g, "&lt;").replace(/>/g, '&gt;');
                }
            }, {
                name: 'NAME1',//同步服务1
                hidden: false,
                sortable: false,
                formatter: function (obj, rows, grid) {
                    if (obj != null && obj != "") {
                        var html = "<a href='javascript:void(0);' class='tempo-datagrid-trigger-sync1name' style='text-decoration: none' rowid='" + grid.SYNC1ID + "'>" + obj + "</a>";
                        return html;
                    }
                    return "--";
                }
            }, {
                name: 'NAME2',//同步服务2
                hidden: false,
                sortable: false,
                formatter: function (obj, rows, grid) {
                    if (obj != null && obj != "") {
                        var html = "<a href='javascript:void(0);' class='tempo-datagrid-trigger-sync2name' style='text-decoration: none' rowid='" + grid.SYNC2ID + "'>" + obj + "</a>";
                        return html;
                    }
                    return "--";
                }
            }, {
                name: 'USER_NAME',//发布人
                sortable: false,
                sortable: false
            }, {
                name: 'CREAT_TIME',//发布时间
                hidden: false,
                sortable: true,
                align: "center",
                formatter: function (obj) {
                    if (obj) {
                        return DateUtils.formatDate(new Date(obj), "yyyy-MM-dd HH:mm:ss");
                    }
                    return;
                }
            }, {
                name: 'PRETIME',//上次执行耗时
                align: 'center',
                resizable: false,
                sortable: false,

            }, {
                name: 'FLOWSTATUS',//执行状态
                index: '',
                hidden: false,
                sortable: false,
                formatter: function (obj, grid, rows) {
                    var flowstatus = rows.FLOWSTATUS;
                    if (flowstatus == '1') {
                        return '<span class="running" style="color:rgba(0, 148, 240, 1) ">启用</span>';
                    } else if (flowstatus == "0") {
                        return '<span class="starting" style="color: dimgrey ">禁用</span>';
                    }
                }
            }, {
                title: false,
                name: 'CTYPE',
                index: 'NAME',
                sortable: false,
                formatter: function (obj, grid, rows, state) {
                    var success = rows.successCount || 0;
                    var fail = rows.failedCount || 0;
                    var successNum = success > 100 ? success.toString().substr(0, 2) + "." : success;
                    var failNum = fail > 100 ? fail.toString().substr(0, 2) + "." : fail;
                    return "<button class='state_succ_bt' title='成功" + success + "' style='width: 47px;height: 20px;color:#5185e4;background-color: white;border:1px solid #5185e4;border-radius: 15px;'>" + "成功" + successNum + "</button>" +
                        "<button class='state_fail_bt' title='失败" + fail + "' style='width: 47px;height: 20px;color:#fc7f7f;background-color: white;border:1px solid #fc7f7f;border-radius: 15px;margin-left: 1px;'>" + "失败" + failNum + "</button>";
                }
            }, {
                name: 'rows',
                index: 'NAME',
                sortable: false,
                formatter: function (obj, row, grid, state) {
                    var rowid = grid.GRAYID;
                    var service_status = grid.FLOWSTATUS;
                    if (service_status == '0') {
                        var html = "<span  style='margin-right: 10px' title=' '><a class='tempo-do tempo-gray-start' href='javascript:void(0)'  style='text-decoration: none;' title='启用' serviceId='" + rowid + "'>" + "启用" + "</a></span><span ><a id='tempo-gray-unpublish' class='tempo-gray-unpublish tempo-do' href='javascript:void(0)' style='line-height: 30px;color: #2E90E3;text-decoration: none' title='取消发布' serviceId='" + rowid + "'>" + "取消发布" + "</a></span>";
                    } else {
                        var html = "<span  style='margin-right: 10px'><a class='tempo-do tempo-gray-stop' href='javascript:void(0)' style='text-decoration: none;' title='禁用' serviceId='" + rowid + "'>" + "禁用" + "</a></span><span ><a id='tempo-gray-unpublish' class='tempo-gray-unpublish tempo-do' href='javascript:void(0)' style='line-height: 30px;color: #2E90E3;text-decoration: none' title='取消发布' serviceId='" + rowid + "'>" + "取消发布" + "</a></span>";
                    }
                    return html;
                }
            }
            ],
            loadComplete: function (datas) {
                //解决问题：39697 微服务-挖掘-外网UAT-成果管理：主版本 1点击异步服务的筛选按钮，输入内容之后，筛选符号向上，点击同步服务时，筛选按钮也变成了向上
                $this.find(".tempo-sizer-icon").removeClass("ui-icon tempo-ui-icon tempo-ui-icon-uparrows-thin");
                $this.find(".tempo-sizer-icon").addClass("ui-icon tempo-ui-icon tempo-ui-icon-downarrows-thin");
                $(".ui-state-default").css("padding-left", "0px");
                $(".ui-state-default").css("padding-right", "0px");
                $(".after_select").hide();
                var startSucCount = 0;
                var startFailcount = 0;
                var runningSucCount = 0;
                var runningFailCount = 0;
                var stopSucCout = 0;
                var stopFailCount = 0;
                var allSuccCount = 0;
                var allFailCount = 0;
                var newData = [];
                var searchDataTmp = {};
                if (isSearch) {
                    searchDataTmp = searchData;
                    searchDataTmp.status = "";
                    searchDataTmp.sidx = "";
                    searchDataTmp.sord = "";
                } else {
                    searchDataTmp = {
                        serverName: "",
                        workspaceName: "",
                        jobcreator: "",
                        publishtime_pre: null,
                        publishtime_end: null,
                        status: "",
                        sidx: "",
                        sord: "",
                    };
                }
                $.ajax({
                    url: contextPath + "/api/ai/mine/gray/gray-data-job",
                    type: 'post',
                    data: searchDataTmp,
                    success: function (results) {

                        var rows = results.rows;
                        allDatas = results.rows;
                        for (i = 0; i < rows.length; i++) {
                            if (rows[i].FLOWSTATUS == "1") {
                                if (rows[i].successCount != undefined) {
                                    runningSucCount += rows[i].successCount;
                                    runningFailCount += rows[i].failedCount;
                                    newData.push(rows[i]);
                                } else {
                                    runningSucCount += 0;
                                    runningFailCount += 0;
                                }
                            } else if (rows[i].FLOWSTATUS == "0") {
                                if (rows[i].successCount != undefined) {
                                    startSucCount += rows[i].successCount;
                                    startFailcount += rows[i].failedCount;
                                    newData.push(rows[i]);
                                } else {
                                    startSucCount += 0;
                                    startFailcount += 0;
                                }
                            }
                        }
                        allSuccCount = stopSucCout + startSucCount + runningSucCount;
                        allFailCount = stopFailCount + startFailcount + runningFailCount;
                        if ("running" == nowState) {
                            $(".tempo-task-succeed").val("成功" + runningSucCount);
                            $(".tempo-task-failed").val("失败" + runningFailCount);
                            extendDiv(runningSucCount, $(".tempo-task-succeed"));
                            extendDiv(runningFailCount, $(".tempo-task-failed"));
                        } else if ("unstart" == nowState) {
                            $(".tempo-task-succeed").val("成功" + startSucCount);
                            $(".tempo-task-failed").val("失败" + startFailcount);
                            extendDiv(stopSucCout, $(".tempo-task-succeed"));
                            extendDiv(stopFailCount, $(".tempo-task-failed"));
                        } else {
                            $(".tempo-task-succeed").val("成功" + allSuccCount);
                            $(".tempo-task-failed").val("失败" + allFailCount);
                            extendDiv(allSuccCount, $(".tempo-task-succeed"));
                            extendDiv(allFailCount, $(".tempo-task-failed"));
                        }
                        $("#jqgh_mine-opt-job-grid_cb").css("padding-left", "12px");
                        $("#jqgh_mine-opt-job-grid_cb").parent().css("width", "35px");
                        $(this).data('rows', rows);
                        updatestaticsInfo(rows);
                        bindJobGridEvent.apply(that);
                        grayClickEvent();
                    }
                });
                if (datas.rows.length > 0) {
                    $(".tempo-message").css("display", "none");
                    $('#jobContainer').find('.ui-paging-info').show()
                } else {
                    $('#jobContainer').find('.ui-paging-info').hide();
                    $(".tempo-message").css("display", "");
                    if (nowState == "1") {
                        $(".tempo-message").children().html("暂无数据");
                    } else if (nowState == "0") {
                        $(".tempo-message").children().html("暂无数据");
                    } else {
                        $(".tempo-message").children().html("暂无数据，请在发布区新建灰度服务");
                    }
                }
                var browser = $.support.clearCloneStyle;
                var screenWidth = screen.width;
                if (browser) {
                    $this.find("input.tempo-checkbox+label").css("font-size", "12px");
                } else {
                    if (screenWidth == 1366) {
                        //解决IE11下复选框过大问题
                        $this.find("input.tempo-checkbox+label").css("font-size", "10px");
                    }
                }
                //判断浏览器是否为ie浏览器
                if ((TempoUtils.isIE()) && screenWidth == 1366) {
                    //解决IE11下复选框过大问题
                    $this.find("input.tempo-checkbox+label").css("font-size", "10px");
                }
                //解决1366分辨率下ie11下表格显示一条黑线问题
                // $this.find(".ui-jqgrid-hdiv").css("height", "38px");
                if (navigator.userAgent.indexOf("Firefox") >= 0) {
                    $this.find(".ui-jqgrid-hdiv").css("border-bottom", "0px solid #eee");
                }/* else {
                    $this.find(".ui-jqgrid-hdiv").css("border-bottom", "1px solid #eee");
                }*/
            },
            loadError: function () {
                nowSizerStatus();
            },
            beforeRequest: function () {
                var current_page = $(this).getGridParam("page");//获取要请求的页
                var total_page = $(this).getGridParam("lastpage");//获取总页数
                var cont_page = allDatas.length / $(this).getGridParam("rowNum") + 1;
                if (total_page != 0 && current_page > cont_page) {
                    //当输入页码大于总页码时，加载到最后一页
                    that.grid.datagrid("reloadGridToLastPage", {}, true, true, total_page);
                }
            },
            onSelectAll: function (rowids, status) {
                var multiselect = that.grid.jqGrid().getGridParam("multiselect");
                var rowIds = that.grid.datagrid("getSelectRowIds");
                $(".tempo-datagrid-trigger-name").css("color", "black");
                $(".tempo-datagrid-trigger-sync1name").css("color", "black");
                $(".tempo-datagrid-trigger-sync2name").css("color", "black");
                $(".selectedSpan").text("已选择 " + rowIds.length + " 条");
                if (multiselect && status) {
                    that.grid.jqGrid()
                    $this.find(".after_select").show();
                } else {
                    $this.find(".after_select").hide();
                }
            }
        });
    }
    //筛选框位置计算
    var sxtop = $("#shaix").offset().top;
    var sxleft = $("#shaix").offset().left;
    $("#shaixuanDiv").css("top", sxtop + 30);
    $("#shaixuanDiv").css("left", sxleft - 360);
    var updatestaticsInfo = function (rows) {
        failedCount = 0;
        successCount = 0;
        allCount = rows.length;
        $this.find(".tempo-task-complete").val("全部" + allCount);
        var startSucceedCount = 0;
        var unstart = 0;
        var iftrue = " ";
        for (var i = 0; i < rows.length; i++) {
            iftrue = rows[i].FLOWSTATUS;
            if (iftrue == "1") {
                startSucceedCount++;
            } else {
                unstart++;
            }
        }
        $this.find(".tempo-task-startSucceed").val("启用" + startSucceedCount);
        $this.find(".tempo-task-unstart").val("禁用" + unstart);

        //22463 挖掘-成果监测-成果列表：IE11浏览器下调度状态可以点击，点击时有交互状态，统计数据不需要有交互状态，不可点击
        $this.find(".state_succ_bt").attr("disabled", true);
        $this.find(".state_fail_bt").attr("disabled", true);
        $this.find(".tempo-task-waite").attr("disabled", true);
        $this.find(".tempo-task-running").attr("disabled", true);
        $this.find(".tempo-task-pause").attr("disabled", true);
        $this.find(".tempo-task-succeed").attr("disabled", true);
        $this.find(".tempo-task-failed").attr("disabled", true);
    }

    var initOrrefresh = function (isReloadGrid) {
        if ($this.find('.view-container').height() - 98 > 0) {
            $this.find('.publish_tab').height($this.find('.view-container').height() - 98)
        }
        if (isReloadGrid !== false) {
            initJobGrid();
        }
        $(".ui-paging-info").hide();
        if (allDatas.length == 0) {
            $(".tempo-message").css("display", "");
        } else {
            $(".tempo-message").css("display", "none");
        }
        var form = $this.find('.queryJobSchedulingForm').css("display", "block");
        TempoUtils.parserUi(form, {});
        form.find('[name="starttime"]').datepicker({
            dateFormat: "yy-mm-dd",
            yearRange: "c-100:",
            //设置日期的最大时间和最小时间
            minDate: DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
            maxDate: DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
            changeYear: true,
            changeMonth: true,
            onClose: function (selectedDate) {
                var d = $(this).datepicker('getDate');
                if (d == null) {
                    form.find('[name="endtime"]').datepicker("option", "minDate", null);
                    return;
                }
                var d2 = new Date(d.getTime());
                var d2str = d2.Format('yyyy-MM-dd');
                form.find('[name="endtime"]').datepicker("option", "minDate", d2str);
            },
            onSelect: function (value) {
            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                $.datepicker._hideDatepicker(this);
            }
        }).css("width", "100px");
        form.find('[name="endtime"]').datepicker({
            dateFormat: "yy-mm-dd",
            yearRange: "c-100:",
            //设置日期的最大时间和最小时间
            minDate: DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
            maxDate: DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
            changeYear: true,
            changeMonth: true,
            onSelect: function (value) {
            },
            onClose: function (selectedDate) {
                var d = $(this).datepicker('getDate');
                if (d == null) {
                    form.find('[name="starttime"]').datepicker("option", "maxDate", null);
                    return;
                }
                var d2 = new Date(d.getTime());
                var d2str = d2.Format('yyyy-MM-dd');
                form.find('[name="starttime"]').datepicker("option", "maxDate", d2str);
            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                $.datepicker._hideDatepicker(this);
            }
        }).css("width", "100px");
        //判断当筛选框里是否有值，如没值就将蓝点隐藏
        var if_to_hide = function () {
            // 获取筛选div里的搜索input框
            var inputs = $('#shaixuanDiv').find('input');
            // 定义是否有数据标识 true表示有数据
            var hasValue = false;
            for (var i = 0; i < inputs.length; i++) {
                if (inputs.eq(i).val().trim() != "") {
                    hasValue = true;
                    break;
                }
            }
            // 如果搜索框中有值，则显示图标
            if (hasValue) {
                $("#ifshaixuan").removeAttr('style');
                $(".sizer-reset").css("color", "#5185e4")
            } else {
                $("#ifshaixuan").hide();
            }
        }
        form.find('[name="laststarttime"]').datepicker({
            dateFormat: "yy-mm-dd",
            yearRange: "c-100:",
            //设置日期的最大时间和最小时间
            minDate: DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
            maxDate: DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
            changeYear: true,
            changeMonth: true,
            onClose: function (selectedDate) {
                var d = $(this).datepicker('getDate');
                if (d == null) {
                    form.find('[name="lastendtime"]').datepicker("option", "minDate", null);
                    return;
                }
                var d2 = new Date(d.getTime());
                var d2str = d2.Format('yyyy-MM-dd');
                form.find('[name="lastendtime"]').datepicker("option", "minDate", d2str);
            },
            onSelect: function (value) {
                if_to_hide();
            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                if_to_hide();
            }
        }).css("width", "100px");
        form.find('[name="lastendtime"]').datepicker({
            dateFormat: "yy-mm-dd",
            yearRange: "c-100:",
            //设置日期的最大时间和最小时间
            minDate: DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
            maxDate: DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
            changeYear: true,
            changeMonth: true,
            onSelect: function (value) {
                if_to_hide();
            },
            onClose: function (selectedDate) {
                var d = $(this).datepicker('getDate');
                if (d == null) {
                    form.find('[name="laststarttime"]').datepicker("option", "maxDate", null);
                    return;
                }
                var d2 = new Date(d.getTime());
                var d2str = d2.Format('yyyy-MM-dd');
                form.find('[name="laststarttime"]').datepicker("option", "maxDate", d2str);
            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                if_to_hide();
            }
        }).css("width", "100px");

        form.find('[name="createStartTime"]').datepicker(
            {
                dateFormat: "yy-mm-dd",
                yearRange: "c-100:",
                // 设置日期的最大时间和最小时间
                minDate: DateUtils.formatDate(new Date(new Date()
                    .getFullYear() - 100, 0, 1)),
                maxDate: DateUtils.formatDate(new Date(new Date()
                    .getFullYear() + 1, 0, 1)),
                changeYear: true,
                changeMonth: true,
                width: 50,
                onClose: function (selectedDate) {
                    var d = $(this).datepicker('getDate');
                    if (d == null) {
                        form.find('[name="createEndTime"]').datepicker(
                            "option", "minDate", null);
                        return;
                    }
                    var d2 = new Date(d.getTime());
                    var d2str = d2.Format('yyyy-MM-dd');
                    form.find('[name="createEndTime"]').datepicker(
                        "option", "minDate", d2str);
                },
                onSelect: function (value) {
                    // connectChart();
                },
                onChangeMonthYear: function (year, month, inst) {
                    var month = inst.selectedMonth + 1;
                    var day = inst.selectedDay;
                    var format = function (v) {
                        return String(v).length > 1 ? v : ('0' + v)
                    }
                    $(this).val(
                        inst.selectedYear + '-' + format(month) + '-'
                        + format(inst.selectedDay));
                    $.datepicker._hideDatepicker(this);
                    if_to_hide();
                }
            }).css("width", "100px");
        form.find('[name="createEndTime"]').datepicker(
            {
                dateFormat: "yy-mm-dd",
                yearRange: "c-100:",
                // 设置日期的最大时间和最小时间
                minDate: DateUtils.formatDate(new Date(new Date()
                    .getFullYear() - 100, 0, 1)),
                maxDate: DateUtils.formatDate(new Date(new Date()
                    .getFullYear() + 1, 0, 1)),
                changeYear: true,
                changeMonth: true,
                onSelect: function (value) {
                },
                onClose: function (selectedDate) {
                    var d = $(this).datepicker('getDate');
                    if (d == null) {
                        form.find('[name="createStartTime"]').datepicker(
                            "option", "maxDate", null);
                        return;
                    }
                    var d2 = new Date(d.getTime());
                    var d2str = d2.Format('yyyy-MM-dd');
                    form.find('[name="createStartTime"]').datepicker(
                        "option", "maxDate", d2str);
                },
                onChangeMonthYear: function (year, month, inst) {
                    var month = inst.selectedMonth + 1;
                    var day = inst.selectedDay;
                    var format = function (v) {
                        return String(v).length > 1 ? v : ('0' + v)
                    }
                    $(this).val(
                        inst.selectedYear + '-' + format(month) + '-'
                        + format(inst.selectedDay));
                    $.datepicker._hideDatepicker(this);
                    if_to_hide();
                }
            }).css("width", "100px");
        //筛选框查询操作
        $('.queryBtn').button({
            emphasize: true,
        }).css("width", "60px");
        form.find('.resetBtn').button({
            emphasize: true,
        }).css("width", "60px");

        form.find('.task-opts-btn').button({
            emphasize: true,
            click: function (e) {
            }
        });

        form.find('.task-opts-btn').on("mouseover", function (event) {
            var offset = $(this).offset();
            form.find("#tempo-header-task-opts-infos").css({
                left: offset.left,
                top: offset.top + 26
            });
            form.find("#tempo-header-task-opts-infos").show();
        });

        form.find('.task-opts-btn').on("mouseout", function () {
            form.find("#tempo-header-task-opts-infos").hide();

        });

        form.find("#tempo-header-task-opts-infos").on("mouseover", function () {
            form.find("#tempo-header-task-opts-infos").show();

        })
        form.find("#tempo-header-task-opts-infos").on("mouseout", function () {
            form.find("#tempo-header-task-opts-infos").hide();
        })

    };

    initOrrefresh();

    var openViewDetailDialog = function (job) {

        var paramDialog = $('<div style="width:100%;height:100%;"/></div>').attr("id", 'app-flow-scheduling-execute-detail');
        paramDialog.dialog({
            title: TempoUtils.locale("mine.serviceXiangQing"),
            width: $this.width(),
            height: $this.height(),
            resizable: false,
            modal: true,
            close: function () {
                paramDialog.dialog('destroy');
            },
            open: function () {

                $m.loadPage(contextPath + "/api/ai/app/view/gray_service_view", $(this), job.GRAYID, {"data": job});
                $(".ui-dialog-title").before("<span class='ui-icon tempo-ui-icon tempo-ui-icon-leftarrows-undertint tempo-leftback' style='float: left;margin-top: 12px;'></span>")
                $("#app-flow-scheduling-execute-detail").prev().find("button").css("display", "none")
                $(".ui-draggable-handle").css("cursor", "auto");
                $(".tempo-leftback").css("cursor", "pointer");
                $(".tempo-leftback").click(function () {
                    paramDialog.dialog('destroy');
                    // 请求服务是否存活
                    $this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                    $(".after_select").hide();
                    setTimeout(function () {
                        for (var i = 0; i < 3; i++) {
                            that.grid.setGridParam({loadui: false}).trigger("reloadGrid");
                        }
                    }, 2000);

                });
            }

        });
    };

    var openSync1ViewDetailDialog = function (job) {

        var paramDialog = $('<div style="width:100%;height:100%;"/></div>').attr("id", 'app-flow-scheduling-execute-detail');
        paramDialog.dialog({
            title: TempoUtils.locale("mine.serviceXiangQing"),
            width: $this.width(),
            height: $this.height(),
            resizable: false,
            modal: true,
            close: function () {
                paramDialog.dialog('destroy');
            },
            open: function () {
                $m.loadPage(contextPath + "/api/ai/app/statistics/service_view", $(this), job.SERVICEID, {"data": job});
                $(".ui-dialog-title").before("<span class='ui-icon tempo-ui-icon tempo-ui-icon-leftarrows-undertint tempo-leftback' style='float: left;margin-top: 12px;'></span>")
                $("#app-flow-scheduling-execute-detail").prev().find("button").css("display", "none")
                $(".ui-draggable-handle").css("cursor", "auto");
                $(".tempo-leftback").css("cursor", "pointer");
                Eventbus.trigger('updateStatusLoop.service', job.FLOWID, null, "sync");
                $(".tempo-leftback").click(function () {
                    clearInterval(window.publishTaskStatusInterval);
                    paramDialog.dialog('destroy');
                    $this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                    $(".after_select").hide();
                    setTimeout(function () {
                        for (var i = 0; i < 3; i++) {
                            that.grid.setGridParam({loadui: false}).trigger("reloadGrid");
                        }
                    }, 2000);

                });
            }

        });
    };

    var openSync2ViewDetailDialog = function (job) {

        var paramDialog = $('<div style="width:100%;height:100%;"/></div>').attr("id", 'app-flow-scheduling-execute-detail');
        paramDialog.dialog({
            title: TempoUtils.locale("mine.serviceXiangQing"),
            width: $this.width(),
            height: $this.height(),
            resizable: false,
            modal: true,
            close: function () {
                paramDialog.dialog('destroy');
            },
            open: function () {
                $m.loadPage(contextPath + "/api/ai/app/statistics/service_view", $(this), job.SERVICEID, {"data": job});
                $(".ui-dialog-title").before("<span class='ui-icon tempo-ui-icon tempo-ui-icon-leftarrows-undertint tempo-leftback' style='float: left;margin-top: 12px;'></span>")
                $("#app-flow-scheduling-execute-detail").prev().find("button").css("display", "none")
                $(".ui-draggable-handle").css("cursor", "auto");
                $(".tempo-leftback").css("cursor", "pointer");
                Eventbus.trigger('updateStatusLoop.service', job.FLOWID, null, "sync");
                $(".tempo-leftback").click(function () {
                    clearInterval(window.publishTaskStatusInterval);
                    paramDialog.dialog('destroy');
                    $this.find('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                    $(".after_select").hide();
                    setTimeout(function () {
                        for (var i = 0; i < 3; i++) {
                            that.grid.setGridParam({loadui: false}).trigger("reloadGrid");
                        }
                    }, 2000);
                });
            }
        });
    };

    //初始化成果管理页面页面变动监听事件
    var timeout = 0;
    window.addEventListener('resize', function () {
        if (timeout != 0) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(function () {
            that.grid.datagrid("reloadGrid");
            //调整弹框宽度
            if ($this.find("#app-flow-scheduling-execute-detail").length > 0) {
                $this.find("#app-flow-scheduling-execute-detail").parent().css("width", $this.width());
                if ($this.find("#app-flow-scheduling-execute-detail").find(".tempo-head-li").length > 0) {
                    var tempoHeadLis = $this.find("#app-flow-scheduling-execute-detail").find(".tempo-head-li");
                    for (var i = 0; i < tempoHeadLis.length; i++) {
                        var $tempoHeadLi = $(tempoHeadLis[i]);
                        if ($tempoHeadLi.css("border-bottom") == '2px solid rgb(31, 115, 182)') {
                            //触发选中页签的点击事件，重新触发页面样式
                            $tempoHeadLi.trigger("click");
                            break;
                        }
                    }
                }
            }
            timeout = 0;
        }, 200)
    });
});